<?php

/**
 * Holds class Mvc_Dispatcher
 *
 * @author Mark
 *
 * @package Library
 * @subpackage Mvc
 */

/**
 * Dispatcher
 *
 * @todo write comment
 *
 * @author Mark
 */
class Mvc_Dispatcher {

	/**
	 * Controller context resource
	 * @var Mvc_Context_Controller $_controllerContext
	 */
	protected $_controllerContext;

	/**
	 * Request resource
	 * @var Mvc_Request $_request
	 */
	protected $_request;

	/**
	 * View context resource
	 * @var Mvc_Context_View $_viewContext
	 */
	protected $_viewContext;

	/**
	 * Constructor
	 *
	 * @param Mvc_Request $request
	 * @return void
	 */
	public function __construct(Mvc_Request $request) {
		$this->_request = $request;
	}

	/**
	 * Dispatches
	 *
	 * @param string $filename
	 * @return boolean|Mvc_Response
	 */
	public function dispatch($filename) {
		if(!file_exists($filename)) {
			return false;
		}
		require_once $filename;

		$module = $this->_request->getModule();
		$controller = $this->_request->getController();
		$action     = $this->_request->getAction();

		// Initialize
		if(class_exists($controller) && in_array($action, get_class_methods($controller))) {
			$class = new $controller;
			$class->setContext($this->_controllerContext)
				->setLayout($module,$controller,$action)
				->setArguments($this->_request->getAllParams());
				
			if(200 == $class->getResponse()->getStatus()){
				$class->$action($this->_request->getAllParams());
			}

			return $class->render()->getResponse();
		}
		return false;
	}

	/**
	 * Sets controller context resource
	 *
	 * @param Mvc_Context_Controller $controllerContext
	 * @return Mvc_Dispatcher (fluent interface)
	 */
	public function setControllerContext(Mvc_Context_Controller $controllerContext) {
		$this->_controllerContext = $controllerContext;
		return $this;
	}

	/**
	 * Sets view context resource
	 *
	 * @param Mvc_Context_View $viewContext
	 * @return Mvc_Dispatcher (fluent interface)
	 */
	public function setViewContext(Mvc_Context_View $viewContext) {
		$this->_viewContext = $viewContext;
		return $this;
	}

}
